package io.task.cc.network.maintain;

import io.task.cc.network.ChannelContext;
import io.task.cc.network.utils.lock.LockedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * 一对一  (ChannelContext.id <--> ChannelContext)<br>
 */
public class Ids {
    private static final Logger log = LoggerFactory.getLogger(Ids.class);

    /**
     * key: ChannelContext对象的id字段
     * value: ChannelContext
     */
    private final LockedMap<String, ChannelContext> map = new LockedMap<>(new HashMap<String, ChannelContext>());


    public void bind(ChannelContext channelContext) {

        try {
            String key = channelContext.getId();
            if (key == null) {
                return;
            }
            map.put(key, channelContext);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    /**
     * Find.
     */
    public ChannelContext find(String id) {


        if (id == null) {
            return null;
        }

        return map.get(id);
    }


    public void unbind(ChannelContext channelContext) {

        try {
            String key = channelContext.getId();
            if (key == null) {
                return;
            }
            map.remove(key);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }
}
